﻿using Elasticsearch.Synchronize.Domain.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Elasticsearch.Synchronize.Domain.Aggregates.SynchronizeAggregate;
using Elasticsearch.Synchronize.Repository.Interface;
using Elasticsearch.Synchronize.Repository.MongoDbDTO;
using MongoDB.Driver;
using AutoMapper;

namespace Elasticsearch.Synchronize.Repository.Repository
{
    public class SynchronizeRuleRepository : ISynchronizeRuleRepository
    {
        private readonly IMongoDbContext _context;

        public SynchronizeRuleRepository(IMongoDbContext contex)
        {
            _context = contex;
        }

        public List<SynchronizeRule> GetValidRules()
        {
            var filter = Builders<SynchronizeRuleDTO>.Filter.Eq(t => t.Enabled, true);
            var result = _context.SynchronizeRule.FindSync(filter).ToList();
            return Mapper.Map<List<SynchronizeRuleDTO>, List<SynchronizeRule>>(result);
        }

        public void Update(string identity, SynchronizeRule rule)
        {
            var filter = Builders<SynchronizeRuleDTO>.Filter.Eq(f => f.RuleId, identity);
            var existedRule = _context.SynchronizeRule.Find(filter).FirstOrDefault();


            var update = Builders<SynchronizeRuleDTO>.Update
                .Set(t => t.RuleFilter, existedRule.RuleFilter);

            var updateResult = _context.SynchronizeRule.UpdateOne(filter, update);
        }
    }
}